package com.hsogoo.avatar.demo;

import com.google.gson.Gson;
import com.hsogoo.avatar.demo.handler.DemoClientHandler;
import com.hsogoo.avatar.model.AvatarRequest;
import com.hsogoo.avatar.model.AvatarResponse;
import com.hsogoo.avatar.transport.AvatarFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author huangsaigang
 * Created @2018/10/1.
 */
public class DemoConnector2 {

    private final static int port = 8888;
    private final static String host = "localhost";
    private final static Bootstrap b = new Bootstrap();
    private static ChannelFuture f = null;

    public static void main(String[] args) {

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new DemoClientHandler());
                ch.pipeline().addLast(new StringEncoder());
            }
        });

        try {
            // Start the client.
            f = b.connect(host, port).sync(); // (5)

            AvatarRequest request = new AvatarRequest();
            request.setRequestId("123456");
            request.setInterfaceName("className");
            request.setMethodName("methodName");

            String requestStr = new Gson().toJson(request);
            f.channel().writeAndFlush(requestStr);
            f.channel().writeAndFlush("\r\n");
            AvatarFuture af = new AvatarFuture(request);
            AvatarResponse response = af.get();
            System.out.println(response);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }

}
